import numpy as np
import cv2 as cv
from matplotlib import pyplot as plt


def thresh_image(src):
    img = cv.imread(src)
    ex = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
    ex = cv.GaussianBlur(ex, (9, 9), 0)
    ex = cv.adaptiveThreshold(ex, 255, cv.ADAPTIVE_THRESH_MEAN_C, cv.THRESH_BINARY, 11, 10)
    return img, ex


img1, ex1 = thresh_image('t3.jpg')

contours, hierarchy = cv.findContours(ex1, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)
ellipses = []
i = 0
for cnt in contours:
    if cnt.shape[0] >= 5 and 1000 < cv.contourArea(cnt) < 20000 and cv.arcLength(cnt, closed=True) < 1000:
        print(cv.contourArea(cnt), cv.arcLength(cnt, closed=True))
        ellipse = cv.fitEllipseAMS(cnt)
        if len(ellipses) == 0:
            ellipses.append(ellipse)
            cv.ellipse(img1, ellipse, (0, 0, 255), 5)
            print(ellipse)
        else:
            if abs(sum(ellipse[0]) - sum(ellipses[i][0])) >= 10 or abs(
                    sum(ellipse[0]) - sum(ellipses[i][0])) <= 10 and abs(sum(ellipse[1]) - sum(ellipses[i][1])) >= 50:
                ellipses.append(ellipse)
                i += 1
                cv.ellipse(img1, ellipse, (0, 0, 255), 5)
                print(ellipse)
print(len(ellipses))

# circles = cv.HoughCircles(ex1, cv.HOUGH_GRADIENT, 1, 50, param1=50, param2=25, minRadius=4, maxRadius=200)
# circles = np.uint16(np.around(circles))
# circles = circles[0, :]
# print(circles)
# for i in circles:
#     cv.circle(img1, (i[0], i[1]), i[2], (0, 255, 0), 10)


plt.subplot(1, 2, 1), plt.imshow(ex1, cmap='gray')
plt.subplot(1, 2, 2), plt.imshow(img1[:, :, ::-1])
plt.show()
